require(['../../common'], function() {
  require(['content.ad'])
})

define('content.ad', [
  'jquery',
  'page/grid'
], function($, Grid) {
  'use strict';
  var $table = $('.table')
  var mygrid = new Grid($table)
  mygrid.init()

  $(document)
    .on('click', '.A_del', function(e) {
      e.preventDefault()
      var current = mygrid.getCurrent(this)
      var selected = {
        id: [current.id],
        index: [current.index]
      }
      deleteAd(selected)
    })
    .on('click', '#J_del', function(e) {
      e.preventDefault()
      var selected = mygrid.getSelected()
      if (!selected.count) {
        alert(lang.pleaseSelectAData)
        return
      }
      deleteAd(selected)
    })
    // 排序
  .on('click', '.moveup', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) - 1), 'up')
  })

  // 排序
  .on('click', '.movedown', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) + 1), 'down')
  })

  function deleteAd(selected) {
    $.post(APP + '?app=admin&m=Content&a=deleteAd', {
      ids: selected.id.join()
    })
      .done(function(res) {
        if (res == '1') {
          alert(lang.delSuccess)
          mygrid.del(selected.index)
        } else {
          alert(lang.delFails)
        }
      })
  }

  function move(id, el, index, nextIndex, direction) {
    var baseid = direction == 'up' ? $(el).closest('tr').prev().data('id') : $(el).closest('tr').next().data('id');
    if (baseid) {
      $.post(APP + '?app=admin&m=Content&a=moveAd', {
    	ad_id: id,
        baseid: baseid
      }).done(function(res) {
        if (res === '1') {
          mygrid.swap(index, nextIndex)
        }
      })
    }
  }

})
